package com.itheima.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("*******哈哈，你被拦截了！！11111111******");
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //1 获取请求路径url
        String url = request.getRequestURL().toString();
        //2 判断是否是登录请求
        if (url.contains("login")) {
            //登录，直接放行
            filterChain.doFilter(servletRequest,servletResponse);

            System.out.println("*******哈哈，你被拦截了！！222222******");

            return;
        }

        //3 获取请求头
        String jwt = request.getHeader("token");


        //4 判断是否存在token
        if (jwt == null) {
            notLoginResponse(servletResponse);

            //拦截
            return;
        }

        //5 解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        } catch (Exception e) {
            e.printStackTrace();
            //令牌失效
            notLoginResponse(servletResponse);
        }





    }

    /**
     * 返回结果
     * @param servletResponse
     * @throws IOException
     */
    private void notLoginResponse(ServletResponse servletResponse) throws IOException {
        //返回统一NOT_LOGIN结果给前端
        Result errorResult = Result.error("NOT_LOGIN");
        //怎么把errorResult对象转换为JSON字符串？
        //java对象  JSON之间的映射
        ObjectMapper objectMapper = new ObjectMapper();
        //把java对象变成json字符串
        String json = objectMapper.writeValueAsString(errorResult);

        //返回到前端
        servletResponse.getWriter().write(json);
    }
}


